package com.leyou.cart.service;

import com.leyou.cart.pojo.Cart;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {
    @Autowired
     private StringRedisTemplate redisTemplate;
    public void addCart(Cart cart) {
        //1.查询当前登录用户的购物车数据
        BoundHashOperations<String, Object, Object> boundHashOps = getLoginUserCart();

        //2.判断当前商品是否在购物车中
        String skuId = cart.getSkuId().toString();
        if (boundHashOps.hasKey(skuId)){
            String json = (String) boundHashOps.get(skuId);
            Cart oldcart = JsonUtils.toBean(json, Cart.class);
            cart.setNum(oldcart.getNum()+cart.getNum());
        }
        boundHashOps.put(skuId,JsonUtils.toString(cart));
    }
    /**
     * 获取登录用户的购物车数据
     */
    public BoundHashOperations<String,Object,Object> getLoginUserCart(){
        UserInfo user = UserHolder.getUser();
        Long userId = user.getId();
        //2）到redis中取出我的购物车
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(userId.toString());
        return boundHashOps;
    }

    public List<Cart> loadCats() {

        BoundHashOperations<String, Object, Object> operations = getLoginUserCart();

        List<Cart> cartList = operations.values().stream().map(json -> JsonUtils.toBean((String) json, Cart.class)).collect(Collectors.toList());
        return cartList;
    }

    public void updateNum(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> operations = getLoginUserCart();
        String skuIdstr = skuId.toString();

        String  json = (String) operations.get(skuIdstr);

        Cart cart = JsonUtils.toBean(json, Cart.class);

        cart.setNum(num);

        operations.put(skuIdstr,JsonUtils.toString(cart));

    }

    public void deleteCart(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getLoginUserCart();

        String skuIdstr = skuId.toString();

        operations.delete(skuIdstr);

    }

    public void mergeCarts(List<Cart> carts) {
        carts.forEach(cart -> addCart(cart));
    }
}
